"""DNS API路由."""

from typing import List, Optional

from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.ext.asyncio import AsyncSession

from netsphere.core.database import get_db
from netsphere.services.dns import DNSManager, DNSResolver, ZoneManager
from netsphere.schemas.dns import (
    DNSViewCreate,
    DNSViewResponse,
    DNSZoneCreate,
    DNSZoneUpdate,
    DNSZoneResponse,
    DNSRecordCreate,
    DNSRecordUpdate,
    DNSRecordResponse,
    DNSQueryRequest,
    DNSQueryResponse,
    ZoneStats,
    ZoneValidation,
    ZoneExport,
)

router = APIRouter(prefix="/dns", tags=["dns"])


@router.post("/views", response_model=DNSViewResponse)
async def create_dns_view(
    view: DNSViewCreate,
    db: AsyncSession = Depends(get_db),
):
    """创建DNS视图."""
    manager = DNSManager(db)
    return await manager.create_view(**view.dict())


@router.post("/zones", response_model=DNSZoneResponse)
async def create_dns_zone(
    zone: DNSZoneCreate,
    db: AsyncSession = Depends(get_db),
):
    """创建DNS区域."""
    manager = DNSManager(db)
    return await manager.create_zone(**zone.dict())


@router.get("/zones", response_model=List[DNSZoneResponse])
async def list_dns_zones(
    view_id: Optional[int] = Query(None, description="视图ID"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    db: AsyncSession = Depends(get_db),
):
    """列出DNS区域."""
    manager = DNSManager(db)
    return await manager.list_zones(view_id=view_id, is_active=is_active)


@router.get("/zones/{zone_id}", response_model=DNSZoneResponse)
async def get_dns_zone(
    zone_id: int,
    db: AsyncSession = Depends(get_db),
):
    """获取DNS区域详情."""
    manager = DNSManager(db)
    zone = await manager.get_zone_by_name(str(zone_id))
    if not zone:
        raise HTTPException(status_code=404, detail="Zone not found")
    return zone


@router.put("/zones/{zone_id}", response_model=DNSZoneResponse)
async def update_dns_zone(
    zone_id: int,
    zone_update: DNSZoneUpdate,
    db: AsyncSession = Depends(get_db),
):
    """更新DNS区域."""
    # TODO: 实现区域更新功能
    raise HTTPException(status_code=501, detail="Not implemented")


@router.post("/zones/{zone_id}/records", response_model=DNSRecordResponse)
async def create_dns_record(
    zone_id: int,
    record: DNSRecordCreate,
    db: AsyncSession = Depends(get_db),
):
    """创建DNS记录."""
    manager = DNSManager(db)
    return await manager.create_record(zone_id=zone_id, **record.dict())


@router.get("/zones/{zone_id}/records", response_model=List[DNSRecordResponse])
async def list_dns_records(
    zone_id: int,
    record_type: Optional[str] = Query(None, description="记录类型"),
    name: Optional[str] = Query(None, description="记录名称"),
    is_active: Optional[bool] = Query(None, description="是否激活"),
    db: AsyncSession = Depends(get_db),
):
    """列出DNS记录."""
    manager = DNSManager(db)
    return await manager.list_records(
        zone_id=zone_id,
        record_type=record_type,
        name=name,
        is_active=is_active,
    )


@router.get("/zones/{zone_id}/records/{record_id}", response_model=DNSRecordResponse)
async def get_dns_record(
    zone_id: int,
    record_id: int,
    db: AsyncSession = Depends(get_db),
):
    """获取DNS记录详情."""
    # TODO: 实现记录详情查询
    raise HTTPException(status_code=501, detail="Not implemented")


@router.put("/zones/{zone_id}/records/{record_id}", response_model=DNSRecordResponse)
async def update_dns_record(
    zone_id: int,
    record_id: int,
    record_update: DNSRecordUpdate,
    db: AsyncSession = Depends(get_db),
):
    """更新DNS记录."""
    # TODO: 实现记录更新功能
    raise HTTPException(status_code=501, detail="Not implemented")


@router.delete("/zones/{zone_id}/records/{record_id}")
async def delete_dns_record(
    zone_id: int,
    record_id: int,
    db: AsyncSession = Depends(get_db),
):
    """删除DNS记录."""
    manager = DNSManager(db)
    success = await manager.delete_record(record_id)
    if not success:
        raise HTTPException(status_code=404, detail="Record not found")
    return {"message": "Record deleted successfully"}


@router.post("/query", response_model=DNSQueryResponse)
async def query_dns(
    query: DNSQueryRequest,
    db: AsyncSession = Depends(get_db),
):
    """DNS查询."""
    resolver = DNSResolver(db)
    records = await resolver.resolve(
        name=query.name,
        record_type=query.record_type,
        zone_name=query.zone_name,
    )
    
    return DNSQueryResponse(
        name=query.name,
        record_type=query.record_type,
        records=[
            {
                "id": record.id,
                "name": record.name,
                "type": record.record_type,
                "value": record.value,
                "ttl": record.ttl,
                "priority": record.priority,
            }
            for record in records
        ],
    )


@router.get("/zones/{zone_id}/stats", response_model=ZoneStats)
async def get_zone_stats(
    zone_id: int,
    db: AsyncSession = Depends(get_db),
):
    """获取区域统计信息."""
    zone_manager = ZoneManager(db)
    return await zone_manager.get_zone_stats(zone_id)


@router.get("/zones/{zone_id}/validate", response_model=ZoneValidation)
async def validate_zone(
    zone_id: int,
    db: AsyncSession = Depends(get_db),
):
    """验证区域配置."""
    zone_manager = ZoneManager(db)
    return await zone_manager.validate_zone_config(zone_id)


@router.get("/zones/{zone_id}/export", response_model=ZoneExport)
async def export_zone(
    zone_id: int,
    db: AsyncSession = Depends(get_db),
):
    """导出区域配置."""
    zone_manager = ZoneManager(db)
    
    # 获取区域信息
    manager = DNSManager(db)
    zone = await manager.get_zone_by_name(str(zone_id))
    if not zone:
        raise HTTPException(status_code=404, detail="Zone not found")
    
    # 导出区域内容
    content = await zone_manager.export_zone(zone_id)
    
    return ZoneExport(
        zone_name=zone.name,
        content=content,
        serial=zone.serial,
        created_at=zone.updated_at,
    )


@router.get("/search")
async def search_dns_records(
    name: str = Query(..., description="搜索名称"),
    record_type: Optional[str] = Query(None, description="记录类型"),
    db: AsyncSession = Depends(get_db),
):
    """搜索DNS记录."""
    manager = DNSManager(db)
    return await manager.search_records(name=name, record_type=record_type)